package com.fingard.dsp.bank.directbank.sjcb01;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.IBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.ReqQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.RetAtsQryBatPayRec;
import com.fingard.dsp.bank.reqrespobj.batpayrec.detail.RetAtsBatPayRecDetail;
import com.fingard.dsp.bank.reqrespobj.single.detail.ReqPayRecDetail;
import com.fingard.io.FileHelper;
import com.fingard.net.FtpReceiver;
import com.fingard.text.StringHelper;

/**
 * @author XueJy on 2018/8/31.
 * @version 1.0
 */
public class SJCB01BatPayRec extends SJCB01Base implements IBatPayRec {

    DecimalFormat df = new DecimalFormat("0.00");

    @Override
    public RetAtsBatPayRec d_1988_BatPay(ReqBatPayRec p_req1988) throws Exception {
        return null;
    }

    @Override
    public RetAtsQryBatPayRec d_1998_QryBatPay(ReqQryBatPayRec p_req1998) throws Exception {
        return null;
    }

    @Override
    public RetAtsBatPayRec d_9188_BatPay(ReqBatPayRec p_req9188) throws Exception {

        RetAtsBatPayRec retAts = new RetAtsBatPayRec(p_req9188.reqHeader);
        StringBuilder paymentBuilder = new StringBuilder();
        String[] recMeg = getBankConfig().getMapValueByKey("params", p_req9188.ownAct).split("\\|");
        if (recMeg.length < 2) {
            retAts.respCode = "-1";
            retAts.respInfo = "DSP配置文件未配置相应帐号的 单位编号|业务种类";
            retAts.writeRetToATS();
            return retAts;
        }
        //加密标志，默认0
        paymentBuilder.append("JIAMBZ:0\r\n");
        //单位编号
        paymentBuilder.append("DANWBH:" + recMeg[0] + "\r\n");
        //业务种类
        paymentBuilder.append("YWZLBH:" + recMeg[1] + "\r\n");
        //账户类型
        paymentBuilder.append("KHZHLX:1\r\n");
        //客户账号，默认为空
        paymentBuilder.append("KEHUZH:\r\n");
        //币种
        paymentBuilder.append("HUOBDH:" + convertCurToBank(p_req9188.ownCur) + "\r\n");
        //钞汇标志固定为0
        paymentBuilder.append("CHUIBZ:0\r\n");
        //账户性质
        paymentBuilder.append("ZHHUXZ:0001\r\n");
        //收付标志2-批量代扣
        paymentBuilder.append("SHOFBZ:2\r\n");
        //总金额
        paymentBuilder.append("ZONGJE:" + df.format(new BigDecimal(p_req9188.totalAmt)) + "\r\n");
        //总笔数
        paymentBuilder.append("BISHUU:" + p_req9188.totalNum + "\r\n");
        //入账日期
        paymentBuilder.append("RUZHRQ:" + Format.Date8Format.format(p_req9188.getPayDateOnly()) + "\r\n");
        //明细部分
        paymentBuilder.append("---------------------------------\r\n");
        int count = 1;
        while (p_req9188.readRecord()) {
            ReqPayRecDetail reqDetail = p_req9188.readedDetail;
    /*  01260010236547987|马小虎|100.00|中山路80号|工资|1|
            01000010236547987|王一|100.00|电话80601234|工资|2|
            01000010236547986|周一|100.00|slw|test|3|*/
            //账号|姓名|金额 |备注|摘要|序号|
            String spliter = "|";
            paymentBuilder.append(reqDetail.payAct);
            paymentBuilder.append(spliter);
            paymentBuilder.append(reqDetail.payName);
            paymentBuilder.append(spliter);
            paymentBuilder.append(df.format(new BigDecimal(reqDetail.payAmount)));
            paymentBuilder.append(spliter);
            //摘要存流水
            paymentBuilder.append(reqDetail.askNumber);
            paymentBuilder.append(spliter);
            paymentBuilder.append(reqDetail.useType);
            paymentBuilder.append(spliter);
            paymentBuilder.append(count);
            paymentBuilder.append(spliter);
            paymentBuilder.append("\r\n");
            count++;
        }
        paymentBuilder.delete(paymentBuilder.length() - 2, paymentBuilder.length());

        String batchNO = p_req9188.reqBatchNO;

        //上传文件名，来盘文件名规则：保险公司名_日期_01
        String bakUpPath = getDataFileDirectory(p_req9188.getPayDateOnly());
        int maxBatch = 0;
        File dataFileDir = new File(StringHelper.trimEnd(bakUpPath, File.separator) + File.separator + "batRec");
        if (dataFileDir.exists()) {
            int len = dataFileDir.listFiles().length;
            if (len > 0) {
                maxBatch = len + 1;
            } else {
                maxBatch = 1;
            }
        } else {
            maxBatch = 1;
        }
        String recFileName = bankFront.org + "_" + Format.Date8Format.format(p_req9188.getPayDateOnly()) + "_" + String.format("%2s", maxBatch).replace(" ", "0");
        String tmpBatRecPath = StringHelper.trimEnd(bakUpPath, File.separator) + File.separator + "batRec" + File.separator + recFileName;
        //批次号文件名映射文件
        String tmpLocalMarkPath = StringHelper.trimEnd(bakUpPath, File.separator) + File.separator + "batFileNameMap" + File.separator + batchNO;
        FileHelper.writeFile(tmpLocalMarkPath, recFileName, getCharset());
        WriteBankLogLn2("批次号映射文件路径: " + tmpLocalMarkPath);
        FileHelper.writeFile(tmpBatRecPath, paymentBuilder.toString(), getCharset());
        WriteBankLogLn2("批量交易上传文件备份路径: " + tmpBatRecPath);

        String[] tmpRes = sendToBank(tmpBatRecPath, recFileName);
        retAts.respCode = "0";
        retAts.reqSeqID = batchNO;
        if ("0".equals(tmpRes[0])) {
            retAts.respInfo = "上传成功";
            retAts.transState = "Uploaded";
            retAts.payInfoCode = "I4001";
        } else if ("-1".equals(tmpRes[0])) {
            retAts.respInfo = "上传通讯失败";
            retAts.transState = "BatchFailed";
            retAts.payInfoCode = "E9999";
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = tmpRes[1];
        }
        retAts.writeRetToATS();
        return retAts;
    }

    @Override
    public RetAtsQryBatPayRec d_9198_QryBatPay(ReqQryBatPayRec p_req9198) throws Exception {
        RetAtsQryBatPayRec retAts = new RetAtsQryBatPayRec(p_req9198.reqHeader);
        String batchNO = p_req9198.reqBatchNO;
        String recFileName = "";
        String dataPath = "";
        String tmpLocalMarkPath = "";
        Calendar queryDate = Calendar.getInstance();
        queryDate.setTime(p_req9198.getBgnDateTime());
        //查找七天内的批次号 支付文件名映射文件
        dataPath = getDataFileDirectory(p_req9198.getBgnDateTime());
        tmpLocalMarkPath = StringHelper.trimEnd(dataPath, File.separator) + File.separator + "batFileNameMap" + File.separator + batchNO;
        File payNameFile = new File(tmpLocalMarkPath);
        if (payNameFile.exists()) {
            recFileName = FileHelper.readFileText(tmpLocalMarkPath, getCharset());
        }
        queryDate.add(Calendar.DAY_OF_YEAR, -1);
        if ("".equals(recFileName)) {
            WriteBankLogLn("该支付提交时间内找不到批次号-发送文件名映射文件");
            retAts.respCode = "-1";
            retAts.respInfo = "找不到批次号-发送文件名映射文件";
            retAts.writeAfterDetail();
            return retAts;
        }
        tmpLocalMarkPath = StringHelper.trimEnd(dataPath, File.separator) + File.separator + "result";
        int totalNum = Integer.parseInt(p_req9198.totalNum);
        int countNum = 0;
        //返回结果详情
        List<RetAtsBatPayRecDetail> details = new ArrayList<RetAtsBatPayRecDetail>();
        try {
            FtpReceiver ftpReceiver = downloadFromFtp(recFileName, tmpLocalMarkPath);
            if (ftpReceiver.isCompleted) {
                WriteBankLogLn("结果文件本地存放路径:" + tmpLocalMarkPath);
                //查看对应文件
                retAts.respCode = "0";
                retAts.reqSeqID = batchNO;
                //成功文件
                String successPath = StringHelper.trimEnd(tmpLocalMarkPath, File.separator) + File.separator + recFileName + "_success";
                //失败
                String failPath = StringHelper.trimEnd(tmpLocalMarkPath, File.separator) + File.separator + recFileName + "_fail";
                if (new File(successPath).exists() && new File(failPath).exists()) {
                    //成功信息
                    String successResult = FileHelper.readFileText(successPath, getCharset());
                    WriteBankLogLn("银行返回成功信息的报文\r\n" + successResult);
                    String[] sucResults = successResult.split("\n");
                    //失败信息
                    String failResult = FileHelper.readFileText(failPath, getCharset());
                    WriteBankLogLn("银行返回失败信息的报文\r\n" + failResult);
                    String[] failResults = failResult.split("\n");
                    if (failResults.length > 4) {
                        for (int i = 4; i < failResults.length; i++) {
                            String[] tmpRes = failResults[i].split("\\|");
                            if (tmpRes.length > 9) {
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                if (tmpRes[1].trim().length() != 0) {
                                    tmpRetDetail.payAct = tmpRes[1].trim();
                                } else {
                                    tmpRetDetail.payAct = tmpRes[2].trim();
                                }
                                tmpRetDetail.payName = tmpRes[3];
                                tmpRetDetail.payAmount = tmpRes[4];
                                //错误代码AAAAAAA 代表成功
                                tmpRetDetail.result = tmpRes[5];
                                if ("".equals(tmpRetDetail.result)) {
                                    tmpRetDetail.result = tmpRes[6];
                                }
                                //错误信息
                                tmpRetDetail.memo = tmpRes[6];
                                tmpRetDetail.postScript = tmpRes[7];
                                tmpRetDetail.payInfoCode = tmpRetDetail.result;
                                details.add(tmpRetDetail);
                                countNum++;
                            }
                        }
                    }
                    if (sucResults.length > 4) {
                        for (int i = 4; i < sucResults.length; i++) {
                            String[] tmpRes = sucResults[i].split("\\|");
                            if (tmpRes.length > 9) {
                                RetAtsBatPayRecDetail tmpRetDetail = new RetAtsBatPayRecDetail();
                                //序号
                                //账号
                                //上送的账号为旧卡号，则这是输出旧卡号
                                //上送的账号为当前正常账号，则这里输出空"
                                //"替换后账号
                                //如果上送的数旧卡号，则这里输出新卡号
                                //如果上送的账号为当前正常账号，则这里输出正常账号"
                                //客户姓名
                                //金额
                                //错误代码，AAAAAAA是成功
                                //错误信息
                                //备注，上送文件明细的备注
                                //摘要，上送文件明细的摘要
                                //序号，上送文件明细的序号
                                //1|                     |  6230000099000558758|得到|120.00|AAAAAAA||蒙班|阎筱涵|1|
                                //2|                     |  6230000099000558683|户籍卡|120.00|AAAAAAA||蒙班|徐睿思|2|
                                if (tmpRes[1].trim().length() != 0) {
                                    tmpRetDetail.payAct = tmpRes[1].trim();
                                } else {
                                    tmpRetDetail.payAct = tmpRes[2].trim();
                                }
                                tmpRetDetail.payName = tmpRes[3];
                                tmpRetDetail.payAmount = tmpRes[4];
                                //错误代码AAAAAAA 代表成功
                                tmpRetDetail.result = tmpRes[5];
                                //错误信息
                                tmpRetDetail.memo = "交易成功。";
                                //对账码
                                tmpRetDetail.postScript = tmpRes[7];
                                tmpRetDetail.payInfoCode = tmpRetDetail.result;
                                details.add(tmpRetDetail);
                                countNum++;
                            }
                        }
                    }
                } else {
                    retAts.respCode = "-1";
                    retAts.respInfo = "本地成功或失败信息文件不存在";
                    retAts.writeAfterDetail();
                    return retAts;
                }
            } else {
                retAts.respCode = "-1";
                retAts.respInfo = "结果文件下载失败:" + ftpReceiver.connMsg;
                retAts.writeAfterDetail();
                return retAts;
            }
        } catch (Exception e) {
            retAts.respCode = "-1";
            retAts.respInfo = "查询异常,信息如下;" + e.getMessage();
            retAts.writeAfterDetail();
            return retAts;
        }
        if (totalNum == countNum) {
            for (RetAtsBatPayRecDetail detail : details) {
                retAts.writeRetDetail(detail);
            }
            retAts.writeAfterDetail();
            return retAts;
        } else {
            retAts.respCode = "-1";
            retAts.respInfo = "返回结果总数与请求 总数不一致,可能回盘文件还未产生";
            retAts.writeAfterDetail();
            return retAts;

        }
    }
}
